
import React, { useState, useEffect, useCallback } from 'react';
import { ChartDataPoint, TrainingParameters, TaskType } from '../types';
import ChartComponent from './ChartComponent';
import { Button, Panel, FileUploader } from './shared';
import { PlayIcon, StopCircleIcon, TrashIcon, UploadCloudIcon } from './icons';
import { simulationService } from '../services/simulationService';
import { ollamaService } from '../services/geminiService';

const generateIdleData = (points = 50) => {
    const data: ChartDataPoint[] = [];
    for (let i = 0; i < points; i++) {
        data.push({ step: i, value: Math.random() });
    }
    return data;
};

interface TrainModelViewProps {
  isGpuBusy: boolean;
  setIsGpuBusy: (isBusy: boolean) => void;
  setStatusMessage: (message: string) => void;
}

const TrainModelView = ({ isGpuBusy, setIsGpuBusy, setStatusMessage }: TrainModelViewProps) => {
  const [isRunning, setIsRunning] = useState(false);
  const [lossData, setLossData] = useState<ChartDataPoint[]>(() => generateIdleData());
  const [accuracyData, setAccuracyData] = useState<ChartDataPoint[]>(() => generateIdleData());
  const [guidance, setGuidance] = useState<string>('系统待机中... 等待训练任务指令。');
  const [params, setParams] = useState<TrainingParameters>({
    batchSize: 16, numEpochs: 5, learningRate: 0.001, momentum: 0.9, numWorkers: 2,
  });
  const [fileName, setFileName] = useState<string | null>(null);
  const [progress, setProgress] = useState({ epoch: 0, step: 0, totalSteps: 0 });
  const [time, setTime] = useState({ start: 0, elapsed: '00:00:00' });

  useEffect(() => {
    let timer: number;
    if (isRunning) {
        timer = window.setInterval(() => {
            const elapsedSeconds = Math.floor((Date.now() - time.start) / 1000);
            const h = String(Math.floor(elapsedSeconds / 3600)).padStart(2, '0');
            const m = String(Math.floor((elapsedSeconds % 3600) / 60)).padStart(2, '0');
            const s = String(elapsedSeconds % 60).padStart(2, '0');
            setTime(t => ({...t, elapsed: `${h}:${m}:${s}`}));
        }, 1000);
    }
    return () => clearInterval(timer);
  }, [isRunning, time.start]);


  const clearState = useCallback(() => {
    setIsRunning(false);
    setIsGpuBusy(false);
    setLossData(generateIdleData());
    setAccuracyData(generateIdleData());
    setGuidance('系统待机中... 等待训练任务指令。');
    setFileName(null);
    setProgress({ epoch: 0, step: 0, totalSteps: 0 });
    setTime({ start: 0, elapsed: '00:00:00' });
    setStatusMessage('状态: 空闲');
  }, [setIsGpuBusy, setStatusMessage]);
  
  const handleStart = () => {
    if (!fileName) {
      setStatusMessage('错误: 请先上传训练JSON文件');
      return;
    }
    setIsRunning(true);
    setIsGpuBusy(true);
    setLossData([]);
    setAccuracyData([]);
    setGuidance('正在初始化训练环境...');
    setTime(t => ({...t, start: Date.now()}));
    
    simulationService.start(params, TaskType.Training, {
      onProgress: (epoch, step, totalSteps, loss, accuracy) => {
        setProgress({ epoch, step, totalSteps });
        setLossData(prev => [...prev, { step: (epoch - 1) * totalSteps + step, value: loss }]);
        setAccuracyData(prev => [...prev, { step: (epoch - 1) * totalSteps + step, value: accuracy }]);
        setStatusMessage(`训练中... [轮次 ${epoch}/${params.numEpochs}] [步骤 ${step}/${totalSteps}]`);
      },
      onEpochComplete: (epoch, loss, accuracy) => {
        setGuidance(`正在为轮次 ${epoch} 生成分析报告...`);
        ollamaService.analyzeTrainingProgress(epoch, lossData, accuracyData).then(setGuidance);
      },
      onComplete: (message) => {
        setStatusMessage(message);
        setIsRunning(false);
        setIsGpuBusy(false);
      },
      onStatusUpdate: setStatusMessage
    });
  };

  const handleStop = () => {
    simulationService.stop();
    setIsRunning(false);
    setIsGpuBusy(false);
    setStatusMessage('任务已由用户手动中止。');
  };

  const handleFileUpload = (file: File) => {
    setFileName(file.name);
    setStatusMessage(`文件已上传: ${file.name}`);
  };

  const handleParamChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setParams(p => ({ ...p, [name]: Number(value) }));
  };

  return (
    <div className="p-4 flex flex-col gap-4 h-full hacker-scrollbar overflow-y-auto">
      <div className="flex gap-4 items-center">
        <FileUploader onFileUpload={handleFileUpload} buttonText="上传训练JSON" disabled={isRunning || isGpuBusy} />
        {fileName && <span className="text-cyan-300 text-sm truncate">已加载: {fileName}</span>}
        <div className="flex-grow" />
        <Button onClick={handleStart} disabled={isRunning || isGpuBusy || !fileName} icon={<PlayIcon className="w-4 h-4" />}>开始训练</Button>
        <Button onClick={handleStop} disabled={!isRunning} icon={<StopCircleIcon className="w-4 h-4" />}>停止</Button>
        <Button onClick={clearState} disabled={isRunning} icon={<TrashIcon className="w-4 h-4" />}>清空</Button>
      </div>
      
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Panel title="训练参数" className="md:col-span-1">
          <div className="space-y-3">
            {Object.entries(params).map(([key, value]) => (
              <div key={key} className="flex items-center justify-between">
                <label className="text-sm text-green-300 capitalize">{key.replace(/([A-Z])/g, ' $1')}</label>
                <input type="number" name={key} value={value} onChange={handleParamChange} disabled={isRunning}
                  className="w-28 bg-gray-900/80 border border-green-500/50 text-green-300 p-1 rounded-sm text-right focus:outline-none focus:ring-1 focus:ring-cyan-500"/>
              </div>
            ))}
          </div>
        </Panel>
        
        <Panel title="实时状态" className="md:col-span-2">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-center">
                <div>
                    <div className="text-sm text-gray-400">当前轮次</div>
                    <div className="text-2xl glow-cyan">{progress.epoch} / {params.numEpochs}</div>
                </div>
                <div>
                    <div className="text-sm text-gray-400">当前步骤</div>
                    <div className="text-2xl glow-cyan">{progress.step} / {progress.totalSteps}</div>
                </div>
                <div>
                    <div className="text-sm text-gray-400">已用时间</div>
                    <div className="text-2xl glow-cyan font-mono">{time.elapsed}</div>
                </div>
                <div>
                    <div className="text-sm text-gray-400">预计剩余</div>
                    <div className="text-2xl glow-cyan font-mono">--:--:--</div>
                </div>
            </div>
        </Panel>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <ChartComponent data={lossData} title="训练损失 (Loss)" lineColor="#ff4d4d" dataKey="value" />
        <ChartComponent data={accuracyData} title="准确率 (Accuracy)" lineColor="#00ffff" dataKey="value" />
      </div>

      <Panel title="Google/gemma-3-4b 分析与指导" className="flex-grow">
        <div className="h-full whitespace-pre-wrap text-sm text-cyan-200 hacker-scrollbar overflow-y-auto" style={{maxHeight: '150px'}}>
            {guidance}
        </div>
      </Panel>
    </div>
  );
};

export default TrainModelView;